import { createDiscreteApi } from "naive-ui";
import { gptSoVitsStore } from "../store/gptSoVits";

export const useGPTSoVits = () => {
  const { message } = createDiscreteApi(["message"]);
  const { setGptSoVitsPort } = gptSoVitsStore();
  const { port, isStart } = storeToRefs(gptSoVitsStore());
  const { chatSettings } = storeToRefs(chatSettingStore());
  const { getSetValue } = chatSettingStore();
  const apiConfig = getSetValue("Gpt-SoVits");
  const isStartHandler = async () => {
    const { error } = await useDefaultRequest.get(
      `http://127.0.0.1:${port.value}/`
    );
    if (!error) {
      isStart.value = true;
    } else {
      isStart.value = false;
    }
    return isStart.value;
  };
  isStartHandler();
  const loading = ref(false);
  const start = async () => {
    if (
      !apiConfig("defaultReferenceAudioText") ||
      !apiConfig("defaultReferenceAudioPath")
    ) {
      return message.error("请先设置默认参考音频和默认参考文本");
    }
    loading.value = true;
    if (await isStartHandler()) return;
    const freePort: number = await Tauri.getFreePort();
    const configs = {};
    ObjectToArray<FormTemplate>(
      chatSettings.value["Gpt-SoVits"].template
    )!.forEach((e) => {
      Reflect.set(configs, e.prop, e.value);
    });
    const listen = await Tauri.gptVitsStart(freePort, configs, (e) => {
      return new Promise((resolve) => {
        const message: string = e.payload.message;
        if (message.indexOf("IocpProactor") !== -1) {
          setGptSoVitsPort(freePort);
          resolve(freePort);
          loading.value = false;
          listen!();
          setTimeout(() => {
            isStartHandler();
          }, 1000);
        }
      });
    });
  };
  const stop = () => {};
  return { start, loading, isStart, stop };
};
